from .utils import (
    api_error_handler,
    logger
)
from .project.index import JianYingTemplateService
from services.video_preview_service import VideoPreviewService
import os
# 添加项目根目录到Python路径
import sys
from datetime import datetime
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from .utils import create_success_response, create_error_response
current_dir = os.path.dirname(__file__)
project_root = os.path.dirname(os.path.dirname(current_dir))
sys.path.insert(0, project_root)


@api_view(['GET'])
@permission_classes([AllowAny])
def health_check(request):

    # 这里可以进行一些其他操作 比如检查数据库连接、外部服务等
    """健康检查接口"""
    return Response({
        "success": True,
        "message": "pyJianYingDraft API 服务正常运行",
        "version": "1.0.0",
        "timestamp": datetime.now().isoformat()
    })

# 创建剪映项目模板 - 支持多种配置（文本、音频等）


@api_view(['POST'])
@permission_classes([IsAuthenticated])
@csrf_exempt
@api_error_handler
def create_jianying_template(request):
    """创建剪映项目模板接口"""
    logger.info("🚀 开始创建剪映项目模板")

    try:
        # 调用服务层处理业务逻辑
        result = JianYingTemplateService.create_template(
            user=request.user,
            template_data=request.data
        )

        return Response(result, status=200)

    except Exception as e:
        logger.error(f"❌ 剪映项目模板创建失败: {str(e)}")
        return Response({
            'success': False,
            'message': f'剪映项目模板创建失败: {str(e)}'
        }, status=500)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
@csrf_exempt
@api_error_handler
def generate_preview_video(request):
    """
    根据JSON配置生成预览视频接口

    请求体:
    - canvas_config: 画布配置
    - text_conf: 文本配置
    - video_conf: 视频配置

    返回:
    - 预览视频URL
    """
    logger.info("🎬 开始生成预览视频")

    try:
        result = VideoPreviewService.generate_preview(request.data)
        logger.info(f"✅ 预览视频生成成功: {result['data']['video_url']}")
        return Response(result)
    except Exception as e:
        logger.error(f"❌ 预览视频生成失败: {str(e)}")
        return Response({
            'success': False,
            'message': f'预览视频生成失败: {str(e)}'
        }, status=500)


@api_view(['GET'])
@api_error_handler
def get_text_animations(request):
    """获取文本动画枚举列表"""
    try:
        from sdk.metadata.animation_meta import Text_intro, Text_outro, Text_loop_anim

        # 转换入场动画
        intro_animations = []
        for animation in Text_intro:
            intro_animations.append({
                "name": animation.name,
                "display_name": animation.value.title,
                "is_vip": animation.value.is_vip,
                "duration": animation.value.duration,
                "description": f"{'VIP - ' if animation.value.is_vip else '免费 - '}{animation.value.title}"
            })

        # 转换出场动画
        outro_animations = []
        for animation in Text_outro:
            outro_animations.append({
                "name": animation.name,
                "display_name": animation.value.title,
                "is_vip": animation.value.is_vip,
                "duration": animation.value.duration,
                "description": f"{'VIP - ' if animation.value.is_vip else '免费 - '}{animation.value.title}"
            })

        # 转换循环动画
        loop_animations = []
        for animation in Text_loop_anim:
            loop_animations.append({
                "name": animation.name,
                "display_name": animation.value.title,
                "is_vip": animation.value.is_vip,
                "duration": animation.value.duration,
                "description": f"{'VIP - ' if animation.value.is_vip else '免费 - '}{animation.value.title}"
            })

        return create_success_response("获取文本动画列表成功", data={
            "intro_animations": intro_animations,
            "outro_animations": outro_animations,
            "loop_animations": loop_animations
        })

    except Exception as e:
        logger.error(f"获取文本动画列表失败: {e}")
        return create_error_response(f"获取文本动画列表失败: {str(e)}")
